//#define __DEBUG__
#define THIS_FILE "x_createmtpriority.sqf"
#include "x_setup.sqf"

#define __vkilled(ktype) _vehicle addEventHandler [#killed, {_this set [count _this, #ktype]; _this call FUNC(MTSMTargetKilled)}]
//TYRGHEN - Added to handle the new armor of buildings making them harder to destroy
#define __buildingdmg _vehicle addEventHandler [#handleDamage, FUNC(checkmtsidehd)]

private ["_poss","_prio_kind","_unit","_objs","_number_of_kind"];
if !(call FUNC(checkSHC)) exitWith {};

__TRACE_1("_this","_this")

_poss = _this;

_number_of_kind = 3;
_prio_kind = (floor (random _number_of_kind)) + 1;
// Special case of towns too close to the base to spawn aerial units
if ((_poss distance D_FLAG_BASE) < 5000 && (_prio_kind in [3])) then {
	while {(_prio_kind in [3])} do {
		_prio_kind = (floor (random _number_of_kind)) + 1;
	};
};

__TargetInfo

[QGVAR(priority_position),_poss] call FUNC(NetSetJIP);
[QGVAR(prio_kind),_prio_kind] call FUNC(NetSetJIP);

if (isMultiPlayer) then {
	sleep (120 + random 60);
};

// Delays spawning the priority objective if a player is standing on it
_objs = _poss nearEntities [["Man", "Air", "Car", "Motorcycle", "Tank"], 150];
if (({if (_x == vehicle _x) then { isPlayer _x } else { isPlayer (driver _x) }} count _objs) > 0) then {
	__TRACE_1("Delaying creation","_objs")
	waituntil {
		sleep 12.314;
		_objs = _poss nearEntities [["Man", "Air", "Car", "Motorcycle", "Tank"], 100];
		((({if (_x == vehicle _x) then { isPlayer _x } else { isPlayer (driver _x) }} count _objs) > 0) || __XJIPGetVar(GVAR(mt_radio_down)));
	};
};

// We cancel the creation either, because the town has been taken in between, or randomly (we don't want events in ALL towns)
if (__XJIPGetVar(GVAR(mt_radio_down)) || {(isMultiPlayer && (random 10 >= 3.5))}) exitWith {
	__TRACE("Canceling Priority Target - conditions not met")
	GVAR(priority_resolved) = true;
	if (!isServer) then {
		[QGVAR(sSetVar), [QGVAR(priority_resolved), true]] call FUNC(NetCallEventCTS);
	};
	[QGVAR(priority_position),[]] call FUNC(NetSetJIP);
};
if (!isMultiPlayer) then {
	_prio_kind = 1;
};
__TRACE_2("Starting creation","_poss","_prio_kind")
_unit = objNull;
_objs = [];
private ["_res"];
switch (_prio_kind) do {
	case 2: {
		_res = [_poss, _prio_kind] call compile preprocessFileLineNumbers "x_mtmissions\priority\x_prio_2.sqf";
		if (!(isNil "_res")) then {
			_unit = _res select 0;
			_objs = _res select 1;
		};
	};
	case 3: {
		_res = [_poss, _prio_kind] call compile preprocessFileLineNumbers "x_mtmissions\priority\x_prio_3.sqf";
		if (!(isNil "_res")) then {
			_unit = _res select 0;
			_objs = _res select 1;
		};
	};
	case 4: {
		_res = [_poss, _prio_kind] call compile preprocessFileLineNumbers "x_mtmissions\priority\x_prio_4.sqf";
		if (!(isNil "_res")) then {
			_unit = _res select 0;
			_objs = _res select 1;
		};
	};
	default {
		_res = [_poss, _prio_kind] call compile preprocessFileLineNumbers "x_mtmissions\priority\x_prio_1.sqf";
		if (!(isNil "_res")) then {
			_unit = _res select 0;
			_objs = _res select 1;
		};
		_prio_kind = 1;
	};
};
__TRACE_3("End","_poss","_unit","_objs")

if (isNull _unit) exitWith {
	__TRACE("Canceling Priority Target - could not create it")
	GVAR(priority_resolved) = true;
	if (!isServer) then {
		[QGVAR(sSetVar), [QGVAR(priority_resolved), true]] call FUNC(NetCallEventCTS);
	};
	[QGVAR(priority_position),[]] call FUNC(NetSetJIP);
};
// As a safety measure...
if (isNil "_objs") then { _objs = [] };

[QGVAR(priority_position),_poss] call FUNC(NetSetJIP);
[QGVAR(prio_kind),_prio_kind] call FUNC(NetSetJIP);
sleep 2.314;

if (!isNil QGVAR(HC_CLIENT_OBJ)) then {
	[QGVAR(defendprio),[GVAR(HC_CLIENT_OBJ)]] call FUNC(NetCallEventSTO);
} else {
	["specops", 0, "basic", 4, (__XJIPGetVar(GVAR(priority_position))) ,50,true] spawn FUNC(CreateInf);
};

if (!(isNull _unit) && { alive _unit }) then {
	[QGVAR(priority_target)] call FUNC(NetCallEventToClients);
};

// This will clean up any objects or stuff created by the priority target
[_unit, __XJIPGetVar(GVAR(current_target_index)), _objs] spawn {
	scriptName "spawn_x_createmtpriority_fixor";
	private ["_unit", "_list", "_objs","_curidx","_pos"];
	PARAMS_3(_unit,_curidx,_objs);
	_pos = getPos _unit;
	sleep 10;
	while {true} do {
		if (!alive _unit || {isNull _unit}) exitWith {};
		sleep 0.01;
		_list = list GVAR(current_trigger);
		#ifndef __TT__
		if ((X_JIPH getVariable QGVAR(campscaptured)) == GVAR(sum_camps) && {("Car" countType _list <= GVAR(car_count_for_target_clear))} && {("Tank" countType _list <= GVAR(tank_count_for_target_clear))} && {("CAManBase" countType _list <= GVAR(man_count_for_target_clear))}) exitWith {};
		#else
		if (((X_JIPH getVariable QGVAR(campscaptured_e)) == GVAR(sum_camps) || {(X_JIPH getVariable QGVAR(campscaptured_w)) == GVAR(sum_camps)}) && {("Car" countType _list <= GVAR(car_count_for_target_clear))} && {("Tank" countType _list <= GVAR(tank_count_for_target_clear))} && {("CAManBase" countType _list <= GVAR(man_count_for_target_clear))}) exitWith {};
		#endif
		
		sleep 19.219;
	};
	if (alive _unit) then {
		sleep 100 + random 60;
		if (alive _unit && _curidx == __XJIPGetVar(GVAR(current_target_index))) then {
			_unit setDamage 1;
			GVAR(priority_resolved) = true;
			if (!isServer) then {
				[QGVAR(sSetVar), [QGVAR(priority_resolved), true]] call FUNC(NetCallEventCTS);
			};
		} else {
			if (isNull _unit && {!GVAR(priority_resolved)} && {_curidx == __XJIPGetVar(GVAR(current_target_index))}) then {
				GVAR(priority_resolved) = true;
				if (!isServer) then {
					[QGVAR(sSetVar), [QGVAR(priority_resolved), true]] call FUNC(NetCallEventCTS);
				};
			};
		};
		[QGVAR(priority_done), false] call FUNC(NetCallEventToClients);
	} else {
		if (isNull _unit && {!GVAR(priority_resolved)} && {_curidx == __XJIPGetVar(GVAR(current_target_index))}) then {
			GVAR(priority_resolved) = true;
			if (!isServer) then {
				[QGVAR(sSetVar), [QGVAR(priority_resolved), true]] call FUNC(NetCallEventCTS);
			};
		};
		[QGVAR(priority_done), true] call FUNC(NetCallEventToClients);
	};
	[QGVAR(priority_position),[]] call FUNC(NetSetJIP);
	sleep 300;
	waituntil { sleep 35.3456; ({isPlayer _x} count (_pos nearEntities ["Man",60])) <= 0 };
	if (count _objs > 0) then {
		{
			if !(isNull _x) then { _x setDamage 1; sleep 0.1; deleteVehicle _x; };
		} foreach _objs;
	};
	deleteVehicle _unit;
	{ if (!(isPlayer _x) && {(count (_x nearTargets 200)) <= 0}) then { _x setDamage 1; } } foreach (_pos nearEntities ["Man",100]);
};